<?php
require('application/classes/api/Utils.php');
require('application/classes/api/label.php');
require('application/classes/api/brand.php');
require('application/classes/api/category.php');
require('application/classes/api/express.php');
require('application/classes/api/china.php');
require('application/classes/api/active.php');
require('application/classes/api/chinatemplate.php');
require('application/classes/api/productdesc.php');
require('application/classes/api/labelproduct.php');
require('application/classes/api/activeconfig.php');

require('application/classes/api/productexpresssku.php');

require('application/classes/api/specification.php');
require('application/classes/api/specificationShow.php');
require('application/classes/api/productstoresku.php');


class product
{

    public function updateStatus($parm)
    {
        DB::update("sysproduct")->set(array('shelves' => $parm['shelves']))
            ->where('id', '=', $parm['id'])->execute();

    }

    public function productCount()
    {
        $result = DB::select('*')->from('sysproduct')->execute()->as_array();
        return $result;
    }

    public function getList($parm)
    {
        $query = DB::query(Database::SELECT,
            'select *,(select name from sysbrand where id=sysproduct.brand ) as brand ,(select name from syscategory where id=sysproduct.category) as category ,(select name from syscategory where id=sysproduct.classification) as classification from sysproduct   limit ' . ($parm['page'] - 1) * $parm['rows'] . ',' . $parm['rows'])->execute()->as_array();
        $count = DB::query(Database::SELECT,
            'select count(1) from sysproduct   ')->execute()->as_array();
        $data['total'] = $count[0]['count(1)'];
        $data['rows'] = $query;
        return $data;
    }

    public function getListShelves($parm)
    {
        $query = DB::query(Database::SELECT,
            'select *,(select name from sysbrand where id=sysproduct.brand ) as brand ,(select name from syscategory where id=sysproduct.category) as category ,(select name from syscategory where id=sysproduct.classification) as classification from sysproduct  where sysproduct.shelves=1  limit ' . ($parm['page'] - 1) * $parm['rows'] . ',' . $parm['rows'])
            ->execute()->as_array();
        $count = DB::query(Database::SELECT,
            'select count(1) from sysproduct  where shelves=1 ')->execute()->as_array();
        $data['total'] = $count[0]['count(1)'];
        $data['rows'] = $query;
        return $data;
    }

    public function detail($parm)
    {
        $data = self::productInitData();
        $result = DB::query(Database::SELECT,
            'select * from sysproduct inner join sysproductdesc on (sysproductdesc.productid=sysproduct.id) where sysproduct.id=' . $parm['id'])->execute()->as_array();
        if (count($result) == 0) {
            throw new Exception("产品不存在", 1);

        }

        $chinatemplate = new chinatemplate();
        $result = $result[0];
        $result['chinatemplate'] = $chinatemplate->getByProductId($parm['id']);

        $specificationShow = new specificationShow();
        $result['specification'] = $specificationShow->get($parm);
        $result['data'] = $data;
        return $result;
    }

    public function getByProductId($parm)
    {
        $data = self::productInitData();
        $result = DB::query(Database::SELECT,
            'select * from sysproduct inner join sysproductdesc on (sysproductdesc.productid=sysproduct.id) where sysproduct.id=' . $parm['id'])->execute()->as_array();
        if (count($result) == 0) {
            throw new Exception("产品不存在", 1);

        }


        return $result;
    }

    public function productInitData()
    {
        $china = new china();
        $data['china'] = $china->getProvince();
        $active = new active();
        $data['active'] = $active->getList();
        $brand = new brand();
        $data['brand'] = $brand->getListBrand();
        $category = new category();
        $data['category'] = $category->category();
        $express = new express();
        $data['express'] = $express->getListExpress();
        return $data;
    }

    public function add($parm)
    {
        try {
            Database::instance()->begin();


            $result = DB::insert("sysproduct", array('expressDefault', 'pricedefault', 'weight', 'productNumber', 'brand', 'category', 'classification', 'title', 'OriginalPrice', 'iscoupon', 'type', 'isget', 'isstore'))
                ->values(array($parm['expressDefault'], $parm['pricedefault'], $parm['weight'], time(), $parm['brand'], $parm['category'], $parm['classification'], $parm['title'], $parm['OriginalPrice'], $parm['iscoupon'], $parm['type'], $parm['isget'], $parm['isstore']))
                ->execute();
            $result = $result[0];
            $mainpic = $parm['mainpic'][0];
            $specification = new specification();
            $activeconfig = new activeconfig();
            $parm['productId'] = $result;
            if (isset($parm['active'])) {
                foreach ($parm['active'] as $key => $value) {
                    $data['productId'] = $result;
                    $data['activeId'] = $value;
                    $activeconfig->insert($data);
                }
            }


            $mainpic = str_replace("\"", "", $mainpic);
             moveUploadFile($mainpic);
            $pics = "";

            foreach ($parm['mainpic'] as $key => $value) {
                if ($key == 0) {
                    continue;
                }

                $value = str_replace("\"", "", $value);
                 moveUploadFile($value);
                $pics = $value . "," . $pics;
            }
            $pics = str_replace("\"", "", $pics);

            $productdesc = new productdesc();
            $productdesc->insert($result, $mainpic, $pics, $parm['content1']);
            $chinatemplate = new chinatemplate();
            if (isset($parm['postFee'])) {
                foreach ($parm['postFee'] as $key => $value) {
                    $parm['templateId'][$key] = intval($parm['templateId'][$key]);
                    $parm['city'][$key] = intval($parm['city'][$key]);
                    $chinatemplate->insert($parm['templateId'][$key], $parm['province'][$key], $parm['city'][$key], $parm['morethan'][$key], $result, $parm['price'][$key], $parm['postFee'][$key]);

                }
            }
            $labelproduct = new labelproduct();
            if (isset($parm['label']) && count($parm['label']) > 0) {
                foreach ($parm['label'] as $key => $value) {
                    $labelproduct->insert($result, $value);

                }
            }
            //设置skuid参数
            self::itemsku($parm);
            Database::instance()->commit();
        } catch (Exception $e) {
            echo $e->getMessage();
            Database::instance()->rollback();
            throw $e;
        }
    }

    public function itemsku($parm)
    {
        $specification = new specification();
        $groupspecification = array();
        $temp = $parm['specificationsname'];

        $groupspecification = array_unique($temp);

        $specificationslist = null;
        $count = 0;

        foreach ($groupspecification as $key => $groupdata) {

            foreach ($parm['model'] as $key1 => $value) {
                $temp = "";
                if ($parm['specificationsname'][$key1] == $groupdata) {
                    $temp = $parm['model'][$key1];
                }

                if ($temp == "") {
                    continue;
                }
                $specificationslist[$parm['specificationsname'][$key1]][$count] = $temp;
                $count++;
            }

        }
        $templist = array();
        $specificationShow = new specificationShow();

        foreach ($groupspecification as $key => $groupdata) {
            array_push($templist, $groupdata);
            foreach ($specificationslist[$groupdata] as $specificationkey => $specificationvalue) {
                $data['specificationsname'] = $groupdata;
                $data['model'] = $specificationvalue;
                $data['productId'] = $parm['productId'];
                $specificationShow->insert($data);
            }
        }
        $data['specificationsgrouy1'] = $specificationslist[$templist[0]];

        if (count($templist) > 1) {
            $data['specificationsgrouy2'] = $specificationslist[$templist[1]];

        }

        if (count($templist) > 2) {

            $data['specificationsgrouy3'] = $specificationslist[$templist[2]];
        }


        foreach ($data['specificationsgrouy1'] as $specificationsgrouy1key => $specificationsgrouy1) {

            $specificationBean = array();
            $specificationBean['status'] = 0;
            $specificationBean['productId'] = $parm['productId'];
            if (!isset($data['specificationsgrouy3']) || count($data['specificationsgrouy2']) == 0) {
                $specificationBean['model1'] = $specificationsgrouy1;
                $specificationBean['model2'] = "";
                $specificationBean['model3'] = "";
                $specification->insert($specificationBean);
            }

            if (isset($data['specificationsgrouy2']) && count($data['specificationsgrouy2']) != 0) {
                foreach ($data['specificationsgrouy2'] as $specificationsgrouy2key => $specificationsgrouy2value) {
                    if (!isset($data['specificationsgrouy3']) || count($data['specificationsgrouy3']) == 0) {

                        $specificationBean['model1'] = $specificationsgrouy1;
                        $specificationBean['model2'] = $specificationsgrouy2value;
                        $specificationBean['model3'] = "";
                        $specification->insert($specificationBean);

                    }
                    if (isset($data['specificationsgrouy3']) && count($data['specificationsgrouy3']) != 0) {
                        foreach ($data['specificationsgrouy3'] as $specificationsgrouy3key => $specificationsgrouy3value) {

                            $specificationBean['model3'] = $specificationsgrouy3value;
                            $specificationBean['model2'] = $specificationsgrouy2value;
                            $specificationBean['model1'] = $specificationsgrouy1;

                            $specification->insert($specificationBean);

                        }
                    }
                }

            }


        }
    }

    public function updateProduct($parm)
    {
        try {
            Database::instance()->begin();

            $chinatemplate = new chinatemplate();
            $productdesc = new productdesc();
            $productdesc->delete($parm);
            $activeconfig = new activeconfig();
            $activeconfig->delete($parm);
            $specification = new specification();

            $parm['productId'] = $parm['id'];
            if (isset($parm['active'])) {
                foreach ($parm['active'] as $key => $value) {
                    $data['productId'] = $parm['id'];
                    $data['activeId'] = $value;
                    $activeconfig->insert($data);
                }
            }


            if (isset($parm['specificationsname']) && $parm['openspecification'] == 1) {
                $productexpresssku = new productexpresssku();
                $productexpresssku->delete($parm);
                $productstoresku = new productstoresku();
                $productstoresku->delete($parm);
                $specificationShow = new specificationShow();
                $specificationShow->delete($parm);
                $productexpresssku = new productexpresssku();
                $productexpresssku->delete($parm);
                $specification->delete($parm);
                self::itemsku($parm);
            }


            DB::update("sysproduct")->set(array('expressDefault' => $parm['expressDefault'], 'pricedefault' => $parm['pricedefault'], 'weight' => $parm['weight'], 'brand' => $parm['brand'], 'category' => $parm['category'], 'classification' => $parm['classification'], 'title' => $parm['title'], 'OriginalPrice' => $parm['OriginalPrice'], 'iscoupon' => $parm['iscoupon'], 'type' => $parm['type'], 'isget' => $parm['isget'], 'isstore' => $parm['isstore']))->where('id', '=', $parm['id'])->execute();
            $result = $parm['id'];
            $mainpic = $parm['mainpic'][0];
            $mainpic = str_replace("\"", "", $mainpic);
            moveUploadFile($mainpic);
            $pics = "";
            foreach ($parm['mainpic'] as $key => $value) {

                if ($key == 0) {
                    continue;
                }
                echo $value;
                $value = str_replace("\"", "", $value);
//                echo $value;
                 moveUploadFile($value);
                $pics = $value . "," . $pics;
            }

//            throw new Exception();
            $pics = str_replace("\"", "", $pics);
            $productdesc->insert($result, $mainpic, $pics, $parm['content1']);
            $chinatemplate = new chinatemplate();
            if (isset($parm['postFee']) && $parm['openexpress'] == 1) {

                $chinatemplate->delete($parm);
                foreach ($parm['postFee'] as $key => $value) {
                    $parm['templateId'][$key] = intval($parm['templateId'][$key]);
                    $parm['city'][$key] = intval($parm['city'][$key]);
                    $chinatemplate->insert($parm['templateId'][$key], $parm['province'][$key], $parm['city'][$key], $parm['morethan'][$key], $result, $parm['price'][$key], $parm['postFee'][$key]);

                }
            }
            $labelproduct = new labelproduct();
            $labelproduct->delete($parm);

            if (isset($parm['label']) && count($parm['label']) > 0) {
                foreach ($parm['label'] as $key => $value) {
                    $labelproduct->insert($result, $value);

                }
            }
            Database::instance()->commit();

        } catch (Exception $e) {
            echo $e->getMessage();
            Database::instance()->rollback();
            throw $e;
        }
    }
}